package com.zenchn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.CustomerVO;
import com.zenchn.entity.HttpDataResult;
import com.zenchn.enums.*;
import com.zenchn.exception.CheckException;
import com.zenchn.exception.CustomException;
import com.zenchn.model.*;
import com.zenchn.service.*;
import com.zenchn.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户转移日志管理控制器
 *
 * @author panbingqi
 * @date 2021-06-04 17:34
 */
@RestController
@RequestMapping(value = "customerTransferWeb")
@Api(value = "客户转移日志模块相关接口", tags = "信息管理-客户转移日志")
@RequiresPermissions("customer:transfer")
public class CustomerTransferWebController {
    private final String MODULE = "信息管理>客户转移日志";

    @Resource
    private RegionService regionService;

    @Resource
    private RegionDetailService regionDetailService;

    @Resource
    private CustomerContactsService customerContactsService;

    @Resource
    private CustomerService customerService;


    @Resource
    private AreasService areasService;

    @Resource
    private CustomerTransferService customerTransferService;

    @Resource
    private AccountService accountService;


    /**
     * 分页获取客户转移日志列表
     *
     * @param keyword
     * @param areasCode
     * @param accountId
     * @param customerType
     * @param startTime
     * @param endTime
     * @param page
     * @param pageSize
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "分页获取客户转移日志列表")
    @ApiOperation(value = "分页获取客户转移日志列表", notes = "分页获取客户转移日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "关键字"),
            @ApiImplicitParam(dataType = "String", name = "areasCode", value = "所属省份"),
            @ApiImplicitParam(dataType = "String", name = "accountId", value = "所属用户"),
            @ApiImplicitParam(dataType = "String", name = "customerType", value = "类型"),
            @ApiImplicitParam(dataType = "Date", name = "startTime", value = "参数名称，开始时间"),
            @ApiImplicitParam(dataType = "Date", name = "endTime", value = "参数名称，结束时间"),
            @ApiImplicitParam(dataType = "Date", name = "transferStartTime", value = "参数名称，转移开始时间"),
            @ApiImplicitParam(dataType = "Date", name = "transferEndTime", value = "参数名称，转移结束时间"),
            @ApiImplicitParam(dataType = "Integer", name = "page", value = "当前第page页"),
            @ApiImplicitParam(dataType = "Integer", name = "pageSize", value = "每页pageSize数量")
    })
    @GetMapping(value = "/list")
    @RequiresPermissions("customer:transfer")
    public ResponseEntity<HttpDataResult<PageInfo>> list(
            @RequestParam(required = false, value = "keyword") String keyword,
            @RequestParam(required = false, value = "areasCode") String areasCode,
            @RequestParam(required = false, value = "accountId") String accountId,
            @RequestParam(required = false, value = "customerType") String customerType,
            @RequestParam(required = false, value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
            @RequestParam(required = false, value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
            @RequestParam(required = false, value = "transferStartTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate transferStartTime,
            @RequestParam(required = false, value = "transferEndTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate transferEndTime,
            @RequestParam(required = false, value = "page", defaultValue = "1") Integer page,
            @RequestParam(required = false, value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpDataResult<PageInfo> result = new HttpDataResult<>(request.getRequestURI());

        final TMiAccountExtend accountExtend = (TMiAccountExtend) request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if (accountExtend == null) {
            throw new CustomException("当前登入账户无数据权限");
        }
        //获取当前登入用户所属省份数据权限
        List<String> areasCodeList = new ArrayList<>();
        if (accountExtend.getRegionCode() != null && !"".equals(accountExtend.getRegionCode().trim())) {
            areasCodeList = getAreasCodeList(accountExtend.getRegionCode().trim());
        }
        if (accountExtend.getAreasCode() != null && !"".equals(accountExtend.getAreasCode()) && !areasCodeList.contains(accountExtend.getAreasCode())) {
            areasCodeList.add(accountExtend.getAreasCode().trim());
        }

        if (areasCodeList.isEmpty()) {
            result.setData(new PageInfo());
        } else {
            LocalDateTime startDate = null;
            if (startTime != null) {
                startDate = LocalDateTime.of(startTime, LocalTime.MIN);
            }
            LocalDateTime endDate = null;
            if (endTime != null) {
                endDate = LocalDateTime.of(endTime, LocalTime.MAX);
            }
            LocalDateTime transferStartDate = null;
            if (transferStartTime != null) {
                transferStartDate = LocalDateTime.of(transferStartTime, LocalTime.MIN);
            }
            LocalDateTime transferEndDate = null;
            if (transferEndTime != null) {
                transferEndDate = LocalDateTime.of(transferEndTime, LocalTime.MAX);
            }

            PageHelper.startPage(page, pageSize);
            PageInfo pageInfo = new PageInfo(customerTransferService.selectDynamicSqlByParameter(keyword, areasCodeList, areasCode, accountId, customerType, startDate, endDate, transferStartDate, transferEndDate));

            List<TMiCustomer> customerList = pageInfo.getList();
            List<CustomerVO> customerVOList = new ArrayList<>();
            for (TMiCustomer customer : customerList) {
                CustomerVO customerVO = new CustomerVO();
                BeanUtils.copyProperties(customer, customerVO);
                //设置区域名称
                TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
                regionDetailExample.createCriteria().andAreasCodeEqualTo(customer.getAreasCode()).andRegionIdNotEqualTo(RegionEnum.NATIONAL_ADMINISTRATIVE_REGION.getId());

                List<String> regionIdList = regionDetailService.selectByExample(regionDetailExample).stream().map(TMiRegionDetail::getRegionId).collect(Collectors.toList());
                if (regionIdList != null && !regionIdList.isEmpty()) {
                    TMiRegionExample regionExample = new TMiRegionExample();
                    regionExample.createCriteria().andRegionIdIn(regionIdList);

                    customerVO.setRegionName(regionService.selectByExample(regionExample).stream().map(TMiRegion::getRegionName).collect(Collectors.joining(",")));
                }
                //设置省级名称
                TSysAreas areas = areasService.selectByPrimaryKey(customer.getAreasCode());
                if (areas != null) {
                    customerVO.setAreasCodeName(areas.getName());
                }
                //设置默认联系人信息
                TMiCustomerContactsExample customerContactsExample = new TMiCustomerContactsExample();
                customerContactsExample.createCriteria().andCustomerIdEqualTo(customer.getCustomerId()).andIsDefaultEqualTo("1");

                List<TMiCustomerContacts> customerContactsList = customerContactsService.selectByExample(customerContactsExample);
                if (customerContactsList != null && !customerContactsList.isEmpty()) {
                    TMiCustomerContacts customerContacts = customerContactsList.get(0);
                    customerVO.setCustomerContacts(customerContacts);
                }
                //设置医院等级
                if (CustomerTypeEnum.AGENT.getType().equals(customer.getCustomerType())) {
                    customerVO.setLevelName(String.valueOf(customer.getLevel()));
                }
                if (CustomerTypeEnum.HOSPITAL.getType().equals(customer.getCustomerType())) {
                    customerVO.setLevelName(CustomerLevelTypeEnum.getHospitalDesc(customer.getLevel()));
                }
                customerVO.setHospitalLevel(CustomerLevelTypeEnum.getHospitalDesc(customer.getLevel()));
                //设置类型名称
                customerVO.setCustomerTypeName(CustomerTypeEnum.getAppDesc(customer.getCustomerType()));
                //设置所属用户名称
                TSysAccount account = accountService.selectByPrimaryKey(customer.getAccountId());
                if (account != null) {
                    customerVO.setAccountName(account.getRealName());
                }
                //设置转移时间
                TMiCustomerTransferExample customerTransferExample = new TMiCustomerTransferExample();
                TMiCustomerTransferExample.Criteria criteria = customerTransferExample.createCriteria();
                criteria.andCustomerIdEqualTo(customer.getCustomerId());
                criteria.andIsEnableEqualTo(CustomerStatusEnum.EFFECTIVE.getUpgradeStatus());
                customerTransferExample.setOrderByClause("create_time desc limit 1");

                List<TMiCustomerTransfer> customerTransferList = customerTransferService.selectByExample(customerTransferExample);
                if (customerTransferList != null && !customerTransferList.isEmpty()) {
                    TMiCustomerTransfer customerTransfer = customerTransferList.get(0);
                    customerVO.setLastTransferTime(customerTransfer.getCreateTime());
                }
                customerVOList.add(customerVO);
            }

            pageInfo.setList(customerVOList);

            result.setData(pageInfo);
        }

        result.setMessage("获取客户转移日志列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 获取省份信息
     *
     * @param regionId
     * @return
     */
    private List<String> getAreasCodeList(String regionId) {
        List<String> areasCodeList = new ArrayList<>();
        TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
        regionDetailExample.createCriteria().andRegionIdEqualTo(regionId);

        List<TMiRegionDetail> regionDetailList = regionDetailService.selectByExample(regionDetailExample);
        if (regionDetailList != null && !regionDetailList.isEmpty()) {
            areasCodeList.addAll(regionDetailList.stream().map(TMiRegionDetail::getAreasCode).collect(Collectors.toList()));
        }
        return areasCodeList;
    }

    /***
     *  新增转移日志
     * @param customerIds
     * @param accountId
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "新增转移日志")
    @ApiOperation(value = "新增转移日志", notes = "新增转移日志")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String[]", allowMultiple = true, name = "customerIds", value = "客户ID数组 示例[1,2,3,4]", required = true),
            @ApiImplicitParam(dataType = "String", name = "customerId", value = "客户ID", required = true)
    })
    @GetMapping(value = "/addTransferRecord/{customerIds}")
    @RequiresPermissions("customer:transfer:transfer")
    public ResponseEntity<HttpDataResult<Boolean>> addTransferRecord(
            @PathVariable("customerIds") String[] customerIds,
            @RequestParam(value = "accountId") String accountId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        if (null == customerIds || customerIds.length == 0) {
            throw new CheckException("需要转移的客户ID异常，转移操作失败！");
        }

        final TSysAccount currAccount = (TSysAccount) request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_INFO.getKey());

        List<String> idList = new ArrayList<>(Arrays.asList(customerIds));

        //维护转移日志表
        for (String id : idList) {
            TMiCustomerTransfer customerTransfer = new TMiCustomerTransfer();
            //查询转移前所属账户
            TMiCustomer beforeCustomer = customerService.selectByPrimaryKey(id);
            if (beforeCustomer != null) {
                customerTransfer.setBeforeAccountId(beforeCustomer.getAccountId());
            }
            customerTransfer.setTransferId(CommonUtils.randomUUID());
            customerTransfer.setCustomerId(id);
            customerTransfer.setAfterAccountId(accountId);
            customerTransfer.setIsEnable(CustomerStatusEnum.EFFECTIVE.getUpgradeStatus());
            customerTransfer.setCreator(currAccount.getAccountId());
            customerTransfer.setCreateTime(LocalDateTime.now());

            customerTransferService.insert(customerTransfer);
        }

        //维护客户表所属账户
        TMiCustomerExample customerExample = new TMiCustomerExample();
        customerExample.createCriteria().andCustomerIdIn(idList);

        TMiCustomer customer = new TMiCustomer();
        customer.setAccountId(accountId);

        customerService.updateByExampleSelective(customer, customerExample);

        result.setData(true);
        result.setMessage("转移成功！");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

}

